package com.zxw.gateway.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.nimbusds.jose.JWSObject;
import com.zxw.common.core.base.constant.SecurityConstants;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.logging.log4j.util.Strings;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URLEncoder;

/**
 * 处理token，存在token：获取token写入request中
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class GlobalFilter  implements org.springframework.cloud.gateway.filter.GlobalFilter, Ordered  {

    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getHeaders().getFirst("Authorization");
        if (request.getPath().toString().equals("/oas/oauth/token")) {
            return chain.filter(exchange);
        }
        if(null == token){
            return chain.filter(exchange);
        }

        // 获取token写入request中
        token = StrUtil.replaceIgnoreCase(token, SecurityConstants.JWT_PREFIX, Strings.EMPTY);
        String payload =StrUtil.toString(JWSObject.parse(token).getPayload());
        request = exchange.getRequest().mutate().header(SecurityConstants.JWT_PAYLOAD_KEY, URLEncoder.encode(payload,"UTF-8"))
            .build();
        exchange = exchange.mutate().request(request).build();
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
